package com.hnkywl.sts.service.fxssh;

import com.google.gson.Gson;
import com.hnkywl.sts.dao.base.BmDao;
import com.hnkywl.sts.dao.base.SjzdsyDao;
import com.hnkywl.sts.dao.base.SjzdzDao;
import com.hnkywl.sts.dao.cggl.CgdDao;
import com.hnkywl.sts.dao.cggl.CgdmxDao;
import com.hnkywl.sts.dao.djgl.JyddDao;
import com.hnkywl.sts.dao.htgl.CghtDao;
import com.hnkywl.sts.dao.htgl.XshtDao;
import com.hnkywl.sts.dao.jkgl.XsOrderDao;
import com.hnkywl.sts.dao.jkgl.XsSettleDao;
import com.hnkywl.sts.dao.organ.CkDao;
import com.hnkywl.sts.dao.organ.NbgsDao;
import com.hnkywl.sts.dao.organ.QyjgDao;
import com.hnkywl.sts.dao.sfgl.SkshDao;
import com.hnkywl.sts.dao.sys.GgDao;
import com.hnkywl.sts.dao.sys.PmDao;
import com.hnkywl.sts.dao.xsgl.GdDao;
import com.hnkywl.sts.dao.xsgl.KhDao;
import com.hnkywl.sts.dao.xsgl.XsdDao;
import com.hnkywl.sts.dao.xsgl.XsmxDao;
import com.hnkywl.sts.dao.zjgl.JzjsDao;
import com.hnkywl.sts.entity.base.Sjzdsy;
import com.hnkywl.sts.entity.base.Sjzdz;
import com.hnkywl.sts.entity.cggl.Cgd;
import com.hnkywl.sts.entity.cggl.Cgdmx;
import com.hnkywl.sts.entity.djgl.Goodses;
import com.hnkywl.sts.entity.djgl.Jydd;
import com.hnkywl.sts.entity.htgl.Cght;
import com.hnkywl.sts.entity.htgl.Fkfs;
import com.hnkywl.sts.entity.htgl.Htmx;
import com.hnkywl.sts.entity.htgl.Xsht;
import com.hnkywl.sts.entity.jkgl.XsOrder;
import com.hnkywl.sts.entity.jkgl.XsSettle;
import com.hnkywl.sts.entity.organ.Ck;
import com.hnkywl.sts.entity.organ.Nbgs;
import com.hnkywl.sts.entity.organ.Qyjg;
import com.hnkywl.sts.entity.sfgl.Sfk;
import com.hnkywl.sts.entity.sys.Bm;
import com.hnkywl.sts.entity.sys.Gg;
import com.hnkywl.sts.entity.sys.Pm;
import com.hnkywl.sts.entity.xsgl.*;
import com.hnkywl.sts.entity.zjgl.Jzjs;
import com.hnkywl.sts.service.base.BmService;
import com.hnkywl.sts.service.base.SjzdzService;
import com.hnkywl.sts.service.base.WebserviceTransService;
import com.hnkywl.sts.util.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.NonUniqueResultException;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.*;

/**
 * 订单及资源相关服务端接口Service
 * Created by Fei on 2015/12/10.
 */
@Service
public class DdzyfwService {
    private XsdDao xsdDao;
    private GdDao gdDao;
    private JyddDao jyddDao;
    private BmService bmService;
    private XshtDao xshtDao;
    private CghtDao cghtDao;
    private GgDao ggDao;
    private SjzdzDao sjzdzDao;
    private SjzdzService sjzdzService;
    private SjzdsyDao sjzdsyDao;
    private CgdmxDao cgdmxDao;
    private KhDao khDao;
    private CgdDao cgdDao;
    private CkDao ckDao;
    private XsSettleDao xsSettleDao;
    private XsOrderDao xsOrderDao;
    private QyjgDao qyjgDao;
    private BmDao bmDao;
    private PmDao pmDao;
    private WebserviceTransService webserviceTransService;
    private XsmxDao xsmxDao;
    private NbgsDao nbgsDao;
    private JzjsDao jzjsDao;
    private SkshDao skshDao;

    /**
     * 接口服务：
     * 查询销售单信息
     *
     * @param orderId
     * @return
     */
    public String findXsdInfo(String orderId) {
        StringBuilder sb = new StringBuilder();
        String str;
        List<Xsd> xsdList = this.xsdDao.findXsdListByOrderId(orderId);
        if (xsdList.size() > 0) {
            sb.append("[");
            for (Xsd xsd : xsdList) {
                sb.append("{")
                        .append("\"order_id\":\"" + orderId + "\",")
                        .append("\"order_num\":\"" + Tools.NullToString(xsd.getXsdh()) + "\",")
                        .append("\"custom\":\"" + Tools.NullToString(xsd.getKh().getQc()) + "\",")
                        .append("\"bill_date\":\"" + Tools.NullToString(xsd.getGkshsj()) + "\",")
                        .append("\"order_details\":" + this.findXsmxInfo(xsd) + "")
                        .append("},");
            }
            str = sb.substring(0, sb.length() - 1);
            str += "]";
        } else {
            str = "[]";
        }
        return str;
    }

    /**
     * 查询销售单明细
     *
     * @param xsd
     * @return
     */
    private String findXsmxInfo(Xsd xsd) {
        StringBuilder sb = new StringBuilder("");
        sb.append("[");
        if (xsd.getXsmxList().size() > 0) {
            for (Xsmx xsmx : xsd.getXsmxList()) {
                Double sumJe = 0.0;
                Double dlfy = 0.0;
                Double realPrice;
                Double orderPrice = Tools.NullToDouble(xsmx.getHsj());
                Double orderWt = Tools.NullToDouble(xsmx.getCk_sbsl());
                for (Jfmx jfmx : xsmx.getJfmxList()) {
                    Double dlfje = jfmx.getDlfje() == null ? 0 : jfmx.getDlfje();
                    Double txje = jfmx.getTxje() == null ? 0 : jfmx.getTxje();
                    Double zjzyf = jfmx.getZjzyf() == null ? 0 : jfmx.getZjzyf();
                    dlfy += dlfje + txje + zjzyf;
                    sumJe += jfmx.getGhje() + dlfy;
                }
                realPrice = CalcUtils.round(sumJe / orderWt, 4);
                sb.append("{")
                        .append("\"goods_name\":\"" + Tools.NullToString(xsmx.getJtwz().getName()) + "\",")
                        .append("\"quality\":\"" + Tools.NullToString(xsmx.getJtwz().getCz()) + "\",")
                        .append("\"spec\":\"" + Tools.NullToString(xsmx.getJtwz().getGgxh()) + "\",")
                        .append("\"mat_id\":\"" + Tools.NullToString(xsmx.getBindNo()) + "\",")
                        .append("\"weight_mode\":\"" + Tools.NullToString(xsmx.getJzfs().getZ()) + "\",")
                        .append("\"num\":\"" + Tools.NullToString(xsmx.getCk_js()) + "\",")
                        .append("\"quantity\":\"" + xsmx.getCk_sbsl() + "\",")
                        .append("\"ht_price\":\"" + xsmx.getHsj() + "\",")
                        .append("\"ht_je\":\"" + Tools.mul(orderPrice, orderWt, 2) + "\",")
                        .append("\"sh_price\":\"" + realPrice + "\",")
                        .append("\"sh_je\":\"" + CalcUtils.round(sumJe, 2) + "\"")
                        .append("},");
            }
            /* 截去最后一个逗号 */
            sb.setLength(sb.length() - 1);
        }
        sb.append("]");
        return sb.toString();
    }

    /**
     * 保存传递过来的物资
     *
     * @param list
     * @return
     */
    @Transactional
    public String saveGd(String sellerName, List<Map<String, Object>> list) {
        String result = "";
        for (Map map : list) {
            String zyh = Tools.NullToString(map.get("resource_serial_number_1"));//资源号
            String clh = Tools.NullToString(map.get("resource_serial_number_1"));//材料号(必填)
            Gd gdTemp = this.gdDao.findGdByCode(clh);
            if (null != gdTemp) {
                throw new RuntimeException("重复挂单!");
            }
            String cghth = Tools.NullToString(map.get("purchase_contract_no"));//采购合同号(可选)
            String schth = Tools.NullToString(map.get("production_contract_no"));//生产合同号(可选)
            String gc = Tools.NullToString(map.get("factory_id"));//工厂(可选)
            String bh = Tools.NullToString(map.get("package_id"));//包号(可选)
            String cpm = Tools.NullToString(map.get("pc"));//产品码(可选)
            String zzyt = Tools.NullToString(map.get("apn"));//最终用途(可选)
            String sfjjzy = Tools.NullToString(map.get("isCompetiveResource"));//是否竞价资源(0否  1是)，2表示仓储库房资源，不用了，业务上交给交易去做了
            String bmqx = Tools.NullToString(map.get("layerDefect"));//表面缺陷
            String cply = Tools.NullToString(map.get("stander_from"));//2仓储过来的资源,3表示国贸过来的资源
            String grf = Tools.NullToString(map.get("guomao_resource_from"));//在交易系统中不做任何业务意义，仅保存其值，待推送订单和撤销物资时传给国贸
            String pm = Tools.NullToString(map.get("stander_name"));//品名,如螺纹钢
            String zylb = Tools.NullToString(map.get("cate"));//建筑钢材,物资的第三类别
            String cz = Tools.NullToString(map.get("material"));//HRB400,材质
            String gg = Tools.NullToString(map.get("spec"));//10*9000,规格
            String cd = Tools.NullToString(map.get("brand"));//中钢牌,产地
            String ck = Tools.NullToString(map.get("warehouse"));//崇明建信库,仓库
            String jbfs = Tools.NullToString(map.get("calculate_type"));//理算,计磅方式
            String sl = Tools.NullToString(map.get("measure_count"));//22,数量
            String sldw = Tools.NullToString(map.get("unit"));//件,数量单位
            String djzl = Tools.NullToString(map.get("measure"));//1.999,单件重量
            String zzl = Tools.NullToString(map.get("total_measure"));//总重量
            String zldw = Tools.NullToString(map.get("weight"));//吨,重量单位
            String tscj = Tools.NullToString(map.get("price"));//3790,同市场价
            String scrq = Tools.NullToString(map.get("production_date"));//2015-07-22,生产日期
            String gcbz = Tools.NullToString(map.get("standard"));//"GB1499.2-2007,钢材标准
            String xsdq = Tools.NullToString(map.get("region"));//崇明,销售地区(可选)
            String bz = Tools.NullToString(map.get("remark"));//备注(可选)
            Gd gd = new Gd();
            gd.setResource_serial_number(zyh);
            gd.setMatNo(clh);
            gd.setPurchase_contract_no(cghth);
            gd.setProduction_contract_no(schth);
            gd.setFactoryId(gc);
            gd.setPackageId(bh);
            gd.setPc(cpm);
            gd.setApn(zzyt);
            gd.setIsCompetiveResource(sfjjzy);//是否竞价资源(0否  1是 2是赎货采购单)
            gd.setLayerDefect(bmqx);
            gd.setStander_from(cply);//2仓储过来的资源,3表示国贸过来的资源
            gd.setGuomao_resource_from(grf);
            gd.setProdDesc(pm);
            gd.setCate(zylb);
            gd.setMaterial(cz);
            gd.setSpec(gg);
            gd.setBrand(cd);
            gd.setWarehouse(ck);
            gd.setWeightMethod(jbfs);//计磅方式
            gd.setMeasureCount(sl);
            gd.setUnit(sldw);
            gd.setMeasure(djzl);
            gd.setTotalMeasure(zzl);
            gd.setWeight(zldw);
            gd.setPrice(tscj);
            gd.setProductionDate(scrq);
            gd.setStandard(gcbz);
            gd.setRegion(xsdq);
            gd.setRemark(bz);
            gd.setZyzt("0");//资源状态
            gd.setDateCreated(new Date());
            gd.setLastUpdated(new Date());
            gd.setSellerName(sellerName);
            this.gdDao.save(gd);
            result = "[{\"code\":\"0\",\"msg\":\"运营系统返回，挂牌成功\",\"resource_serial_number\":\"\",\"resource_serial_number_1\":\"" + clh +
                    "\"}]";
        }
        return result;
    }

    /**
     * 保存交易系统推送的交易订单
     *
     * @param jydd
     * @param bool
     * @return
     */
    @Transactional
    public String saveJydd(Jydd jydd, String supplier, String warehouse, String pmCode, boolean bool, String nbgsName) throws Exception {
        String result;
        String order_sn = Tools.NullToString(jydd.getOrder_sn()); //订单(合同)编号
        String order_id = Tools.NullToString(jydd.getOrder_id()); //订单(合同)编号
        String add_time = DateUtil.msecToDateStr(jydd.getAdd_time(), 0L, true); //订单创建时间
        String pay_time = DateUtil.msecToDateStr(jydd.getPay_time(), 86400 * 1000L, false);//订单支付时间+ 1天
        String expire_time = DateUtil.msecToDateStr(jydd.getExpire_time(), 7948800 * 1000L, true);//订单过期时间 + 92天
        if (StringUtils.isBlank(order_sn) || StringUtils.isBlank(order_id) || StringUtils.isBlank(add_time)) {
            return "[{\"code\" :\"1\",\"message\":\"运营系统返回，订单号、订单id或者订单生成时间为空，order_sn=" + order_sn + ",订单order_id =" + order_id + ",订单时间add_time =" + add_time + "\"}]";
        }
        Gson gson = new Gson();
        List<Jydd> listJydd = new ArrayList<Jydd>();
        if (bool) {
            // 赎货订单
            Jydd jyddTemp = this.jyddDao.checkOrderSn(order_sn);
            // 判断是否重复保存
            if (null != jyddTemp) {
                // 调用接口，如果已经在销售系统签订采购合同，不需要调用接口推送采购合同
                if (StringUtils.isBlank(jydd.getGoodses().get(0).getPurchase_contract_no())) {
                    // 判断是否销售系统挂单
                    if (null != jydd.getGuomao_resource_from() && !StringUtils.equals(jydd.getGuomao_resource_from(), "2")) {
                        jyddTemp.setOrder_type(jydd.getOrder_type());
                        jyddTemp.setPackage_SubItem(jydd.getPackage_SubItem());
                        jyddTemp.setSellType(jydd.getSellType());
                        jyddTemp.setShipped_type(jydd.getShipped_type());
                        this.jyddDao.save(jyddTemp);
                        jydd.setIsCompetiveResource(String.valueOf(Integer.valueOf(jydd.getIsCompetiveResource()) + 2));
                        listJydd.add(jydd);
                        String json = gson.toJson(listJydd);
                        result = this.webserviceTransService.putContractWebServiceArgs(json);
                    } else {
                        result = "[{\"code\" :\"0\",\"message\":\"运营系统返回，成功,order_sn：" + jydd.getOrder_sn() + "\"}]";
                    }
                } else {
                    result = "[{\"code\" :\"0\",\"message\":\"运营系统返回，成功,order_sn：" + jydd.getOrder_sn() + "\"}]";
                }
            } else {
                String khqc = Tools.NullToString(jydd.getBuyer_name());//客户全称
                Double ddze = Tools.NullToDouble(jydd.getGoods_amount()); // 订单总额
                //验证数据的合法性
                result = checkData(khqc, ddze, order_sn, jydd.getGoodses());
                if (StringUtils.equals("0", result)) {
                    // 运营商 A20160523zhp
                    Nbgs nbgs = nbgsDao.findNbgsByQc(nbgsName);
                    if (nbgs == null) {
                        return "[{\"code\":\"1\",\"message\":\"运营系统返回，配置的运营商不存在：" + nbgsName + "\"}]";
                    }
                    jydd.setAdd_time(add_time);
                    jydd.setPay_time(pay_time);
                    jydd.setExpire_time(expire_time);
                    jydd.setDateCreated(new Date());
                    jydd.setLastUpdated(new Date());
                    this.jyddDao.save(jydd);
                    //生成采购合同
                    // P20160422zhp 赎货的，默认成都国贸为上游供应商
                    Cght cght = this.saveCght(jydd, supplier, warehouse, pmCode, nbgs, "1");
                    //生成销售合同
                    Qyjg qyjg = this.qyjgDao.findQyjgByQc(khqc);
                    this.saveXsht(cght, qyjg, "1");
                    //生成采购单，采购明细，实时库存
                    this.saveCgdAndKh(cght, jydd);
                    // 调用接口，如果已经在销售系统签订采购合同，不需要调用接口
                    if (StringUtils.isBlank(jydd.getGoodses().get(0).getPurchase_contract_no())) {
                        Jydd jydd1 = new Jydd();
                        ReflectionUtils.getInstance(jydd1, jydd);
                        jydd1.setIsCompetiveResource(String.valueOf(Integer.valueOf(jydd1.getIsCompetiveResource()) + 2));
                        listJydd.add(jydd1);
                        String json = gson.toJson(listJydd);
                        // 判断是否销售系统挂单
                        if (null != jydd.getGuomao_resource_from() && !StringUtils.equals(jydd.getGuomao_resource_from(), "2")) {
                            result = this.webserviceTransService.putContractWebServiceArgs(json);
                        } else {
                            result = "[{\"code\" :\"0\",\"message\":\"运营系统返回，成功,order_sn：" + jydd.getOrder_sn() + "\"}]";
                        }
                    } else {
                        result = "[{\"code\" :\"0\",\"message\":\"运营系统返回，成功,order_sn：" + jydd.getOrder_sn() + "\"}]";
                    }
                }
            }
        } else {
            // 查询交易订单信息
            Jydd jyddTemp = this.jyddDao.checkOrderSn(order_sn);
            // 判断是否重复保存
            if (null != jyddTemp) {
                result = "[{\"code\" :\"0\",\"message\":\"运营系统返回，成功,order_sn：" + jydd.getOrder_sn() + "\"}]";
            } else {
                // 居中结算订单，不发销售，包括居中结算的赎货业务
                if ("mid".equals(jydd.getExtension())) {
                    String khqc = Tools.NullToString(jydd.getBuyer_name());//客户全称
                    Double ddze = Tools.NullToDouble(jydd.getGoods_amount()); // 订单总额
                    // 验证数据的合法性
                    result = checkData(khqc, ddze, order_sn, jydd.getGoodses());
                    if (StringUtils.equals("0", result)) {
                        // 运营商 A20160523zhp
                        Nbgs nbgs = nbgsDao.findNbgsByQc(nbgsName);
                        if (nbgs == null) {
                            return "[{\"code\":\"1\",\"message\":\"运营系统返回，配置的运营商不存在：" + nbgsName + "\"}]";
                        }
                        jydd.setAdd_time(add_time);
                        jydd.setPay_time(pay_time);
                        jydd.setExpire_time(expire_time);
                        jydd.setDateCreated(new Date());
                        jydd.setLastUpdated(new Date());
                        this.jyddDao.save(jydd);
                        // 生成采购合同 M20160422 居中订单供应商应该取订单卖家
                        String sfjs = "0";
                        // 如果是销售系统挂单，就要在销售系统结算
                        if (jydd.getStander_from().equals("1")) {
                            sfjs = "1";
                        }
                        Cght cght = saveCght(jydd, jydd.getSeller_name(), warehouse, pmCode, nbgs, sfjs);
                        //生成销售合同
                        Qyjg qyjg = this.qyjgDao.findQyjgByQc(khqc);
                        Xsht xsht = this.saveXsht(cght, qyjg, sfjs);
                        //生成采购单，采购明细，实时库存
                        this.saveCgdAndKh(cght, jydd);
                        //生成销售单 ,不是赎货情况
                        if (null == jydd.getDingdan_type() || !jydd.getDingdan_type().equals("1")) {
                            saveXsd(xsht, jydd);
                        }
                        result = "[{\"code\" :\"0\",\"message\":\"运营系统返回，成功,order_sn：" + jydd.getOrder_sn() + "\"}]";
                    }
                } else {
                    // 调用接口
                    listJydd.add(jydd);
                    String json = gson.toJson(listJydd);
                    // 判断是否重复保存
                    if (null != this.jyddDao.checkOrderSn(order_sn)) {
                        // 判断是否销售系统挂单
                        if (null != jydd.getGuomao_resource_from() && !StringUtils.equals(jydd.getGuomao_resource_from(), "2")) {
                            result = this.webserviceTransService.putContractWebServiceArgs(json);
                        } else {
                            return "[{\"code\":\"1\",\"message\":\"运营系统返回，非积微专场，仓储挂单运营系统暂不能处理！\"}]";
                        }
                    } else {
                        jydd.setAdd_time(add_time);
                        jydd.setPay_time(pay_time);
                        jydd.setExpire_time(expire_time);
                        jydd.setDateCreated(new Date());
                        jydd.setLastUpdated(new Date());
                        this.jyddDao.save(jydd);
                        // 判断是否销售系统挂单
                        if (null != jydd.getGuomao_resource_from() && !StringUtils.equals(jydd.getGuomao_resource_from(), "2")) {
                            result = this.webserviceTransService.putContractWebServiceArgs(json);
                        } else {
                            return "[{\"code\":\"1\",\"message\":\"运营系统返回，非积微专场，仓储挂单运营系统暂不能处理！\"}]";
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     * 根据传入的list集合循环更新zyzt
     *
     * @param list
     * @return
     */
    public String cancelGoodsOrder(List<Map<String, Object>> list) {
        String result;
        for (Map<String, Object> map : list) {
            String matno = Tools.NullToString(map.get("resource_serial_number_1"));
            if (StringUtils.isNotBlank(matno)) {
                Gd gd = this.gdDao.findGdByCode(matno);
                if (null != gd) {
                    gd.setZyzt("2");
                    this.gdDao.save(gd);
                }
            }
        }
        result = "[{\"code\":\"0\",\"message\":\"运营系统返回，撤单成功\"}]";
        return result;
    }

    /**
     * 保存采购合同
     *
     * @param jydd
     * @param nbgs
     * @return
     * @throws SQLException
     */
    private Cght saveCght(Jydd jydd, String supplier, String warehouse, String pmCode, Nbgs nbgs, String sfjs) throws SQLException {
        Cght cght = new Cght();
        cght.setHtms("xsms");//销售系统推送过来默认为线上模式
        cght.setCglx("tpcght");//统配采购合同
        cght.setExtension(jydd.getExtension());// 居中订单会有值mid
        cght.setHtbm(this.bmService.getHtbm("CGHT"));
        cght.setSl(17.0);
        cght.setXsxt_htbm(jydd.getOrder_sn());
        // 签订日期
        cght.setQdrq(DateUtil.toDateTime(jydd.getAdd_time()));
        // 投资付款时间
        cght.setFksj(DateUtil.addDays(DateUtil.toDateTime(jydd.getAdd_time()), 1));
        // 供应商,企业机构
        Qyjg qyjg = qyjgDao.findQyjgByQc(supplier);
        if (null == qyjg) {
            throw new RuntimeException("运营系统返回，供应商不存在，请联系运营系统人员增加供应商!" + supplier);
        }
        cght.setSfjs(sfjs);
        cght.setHzf(qyjg);
        // 仓库
        Ck warehouse_name = this.ckDao.findCkByMc(warehouse);
        if (warehouse_name == null) {
            throw new RuntimeException("运营系统返回，到达仓库不存在，请联系运营系统人员增加供应商!" + warehouse);
        }
        cght.setCk(warehouse_name);
        cght.setZt("ybc");
        cght.setCkZt(1);
        cght.setDateCreated(new Date());
        cght.setLastUpdated(new Date());
        cght.setWlfgs(nbgs);//E20160523zhp 物流系统的物流方公司，就是内部公司，就是运营商
        cght.setSbgs(nbgs);//M20160523zhp 还是要用配置的运营商
        cght.setOrderId(jydd.getOrder_id());
        cght.setBzjfs(0);
        cght.setSfhdj(false);
        List<Htmx> cghtmxList = new ArrayList();
        if (jydd.getGoodses() != null) {
            for (Goodses goodses : jydd.getGoodses()) {
                Htmx htmx = new Htmx();
                //规格相关的详细
                Gg gg = this.ggDao.findByPro(goodses.getGoods_name(), goodses.getSpec(), goodses.getMetarial());
                if (gg == null) {
                    gg = new Gg();
                    Pm pm = pmDao.findByCode(pmCode);
                    Bm bm = bmDao.getGgwzbm(pm.getCode());
                    gg.setPm(pm);
                    gg.setCode(bm.getBmz());
                    gg.setDateCreated(new Date());
                    gg.setLastUpdated(gg.getDateCreated());
                    //品名
                    gg.setName(goodses.getGoods_name());
                    //规格型号
                    gg.setGgxh(goodses.getSpec());
                    //材质
                    gg.setCz(goodses.getMetarial());
                    //单位
                    gg.setDw("吨");
                    this.ggDao.save(gg);
                    htmx.setWzgg(gg);
                } else {
                    htmx.setWzgg(gg);
                }

                //数据字典相关的详细
                Sjzdz cdSjzdz = this.sjzdzDao.getSjzdzByBz(goodses.getBrand());
                if (cdSjzdz == null) {
                    cdSjzdz = new Sjzdz();
                    Sjzdsy sjzdsy = this.sjzdsyDao.get(61L);
                    //产地
                    cdSjzdz.setZ(goodses.getBrand());
                    //备注
                    cdSjzdz.setBz(goodses.getBrand());
                    //索引号
                    cdSjzdz.setSjzdsy(sjzdsy);
                    cdSjzdz.setLastUpdated(new Date());
                    cdSjzdz.setDateCreated(new Date());
                    this.sjzdzDao.save(cdSjzdz);
                    htmx.setCd(cdSjzdz);
                } else {
                    htmx.setCd(cdSjzdz);
                }
                Sjzdz sjzdz = this.sjzdzDao.get(22L);
                htmx.setJzfs(sjzdz);
                //件数
                String js = goodses.getQuantity();
                htmx.setSbjs(Double.valueOf(js));
                //重量
                String zl = goodses.getMeasure();
                htmx.setSbsl(Double.valueOf(zl));
                //含税单价
                Double hsj = CalcUtils.round(Tools.NullToDouble(goodses.getPrice()), 4);
                htmx.setHsj(hsj);
                //不含税价
                htmx.setBhsj(hsj / (1 + 0.17));
                //含税金额
                Double hsje = Double.valueOf(js) * Double.valueOf(zl) * hsj;
                htmx.setHsje(CalcUtils.round(hsje, 4));
                htmx.setLastUpdated(new Date());
                htmx.setDateCreated(new Date());
                cghtmxList.add(htmx);
            }
        }
        cght.setHtmxList(cghtmxList);
        this.cghtDao.save(cght);
        return cght;
    }


    /**
     * 保存销售合同
     *
     * @param cght
     * @param qyjg
     */
    private Xsht saveXsht(Cght cght, Qyjg qyjg, String sfjs) {
        Xsht xsht = new Xsht();
        xsht.setZt("ybc");
        xsht.setXslx("kcxs");
        xsht.setHtms("xsms");
        xsht.setExtension(cght.getExtension());// 居中订单会有值mid
        xsht.setXsxt_htbm(cght.getXsxt_htbm());
        //关联采购合同
        xsht.setZddhcght(cght);
        xsht.setWlfgs(cght.getWlfgs());// 运营商、申报公司
        xsht.setSbgs(cght.getSbgs());// 申报公司
        xsht.setHzf(qyjg);// 客户、买家公司
        xsht.setQdrq(cght.getQdrq());
        xsht.setJsrq(new Date());
        xsht.setQddd(cght.getQddd());
        xsht.setJhdd(cght.getJhdd());
        xsht.setHtbm(this.bmService.getHtbm("XSHT"));
        xsht.setLastUpdated(new Date());
        xsht.setSl(17.0);
        xsht.setXsfy(this.sjzdzService.findSjzdzByMc("无费用"));
        xsht.setHtxz(this.sjzdzService.findSjzdzByMc("标准合同"));
        xsht.setMxts(cght.getMxts());
        xsht.setTxl(cght.getTxl());
        xsht.setOrderId(cght.getOrderId());
        xsht.setSfjs(sfjs);
        List<Htmx> xshtmxList = new ArrayList();
        if (cght.getHtmxList() != null) {
            for (int i = 0; i < cght.getHtmxList().size(); i++) {
                Htmx xshtmx = new Htmx();
                xshtmx.setWzgg(cght.getHtmxList().get(i).getWzgg());
                xshtmx.setSbsl(cght.getHtmxList().get(i).getSbsl());
                xshtmx.setSbjs(cght.getHtmxList().get(i).getSbjs());
                xshtmx.setCd(cght.getHtmxList().get(i).getCd());
                xshtmx.setJzfs(cght.getHtmxList().get(i).getJzfs());
                xshtmx.setPh(cght.getHtmxList().get(i).getPh());
                xshtmx.setSpec(cght.getHtmxList().get(i).getSpec());
                xshtmx.setMxh(Long.valueOf((long) (i + 1)));
                xshtmx.setLastUpdated(new Date());
                xshtmx.setZt("ybc");
                xshtmx.setBhsj(cght.getHtmxList().get(i).getBhsj());
                xshtmx.setHsj(cght.getHtmxList().get(i).getHsj());
                xshtmx.setHsje(cght.getHtmxList().get(i).getHsje());
                xshtmxList.add(xshtmx);
            }
        }
        xsht.setHtmxList(xshtmxList);
        xsht.setCk(cght.getCk());
        this.xshtDao.save(xsht);
        return xsht;
    }


    /**
     * 保存采购单及实时库存
     *
     * @param cght
     */
    private void saveCgdAndKh(Cght cght, Jydd jydd) {
        if (null == cght || null == cght.getId()) {
            throw new RuntimeException("运营系统返回，没有查询到对应的采购合同!");
        }

        List<Cgdmx> cgdmxList = new ArrayList<Cgdmx>();
        List<Kh> khList = new ArrayList<Kh>();
        if (jydd.getGoodses() != null) {
            int i = 1;
            for (Goodses goodses : jydd.getGoodses()) {
                String resource_serial_number = goodses.getResource_serial_number();//仓储资源唯一号
                String bindNo = goodses.getResource_serial_number_1().trim(); //捆绑号
                String xsxtXsdh = goodses.getPurchase_contract_no();

                // 判断是否已经保存，防止重复入库，捆包号
                Kh khTemp = this.khDao.findKhByRsn(resource_serial_number, bindNo);
                if (null != khTemp) {
                    continue;
                }
                Integer number = Tools.NullToInteger(goodses.getQuantity());//件数
                Double weight = CalcUtils.round(Double.valueOf(goodses.getMeasure()), 6);//重量
                Double hsj = CalcUtils.round(Tools.NullToDouble(goodses.getPrice()), 4);//含税价
                Cgdmx cgdmx = new Cgdmx();
                cgdmx.setLastUpdated(new Date());
                cgdmx.setBhsj(CalcUtils.round(hsj / 1.17, 4));
                cgdmx.setHsj(hsj);
                cgdmx.setSjdj(hsj);
                cgdmx.setXsxt_xsdh(xsxtXsdh);
                cgdmx.setXsxt_htbm(cght.getXsxt_htbm());
                cgdmx.setBindNo(bindNo);
                Sjzdz sjzdz = this.sjzdzDao.get(22L);
                cgdmx.setJzfs(sjzdz);
                Gg gg = this.ggDao.findByPro(goodses.getGoods_name(), goodses.getSpec(), goodses.getMetarial());
                cgdmx.setGg(gg);

                Sjzdz cdSjzdz = this.sjzdzDao.getSjzdzByBz(goodses.getBrand());
                cgdmx.setCd(cdSjzdz);
                cgdmx.setJs(number);
                cgdmx.setSbsl(weight);
                cgdmx.setRksl(weight);
                cgdmx.setRkjs(number);
                cgdmx.setSsjs(number);
                cgdmx.setSssl(weight);
                cgdmx.setCreateUser(cght.getCreateUser());
                cgdmx.setCreateDepartment(cght.getCreateDepartment());
                cgdmx.setCreateOrgan(cght.getCreateOrgan());
                cgdmx.setMxh((long) i);
                cgdmxDao.save(cgdmx);
                cgdmxList.add(cgdmx);


                //生成卡号
                Kh kh = new Kh();
                kh.setLastUpdated(new Date());
                kh.setCd(cdSjzdz);
                kh.setKhbm(bmService.getKckhbm(cght.getCk().getId()));
                kh.setKkdsl(weight);
                kh.setRksl(weight);
                kh.setRkrq(new Date());
                kh.setSl(weight);
                kh.setWsdj(CalcUtils.round(hsj / 1.17, 4));
                kh.setXsxt_price(hsj);
                kh.setCght(cght);
                kh.setCk(cght.getCk());
                kh.setJtwz(gg);
                kh.setCreateUser(cght.getCreateUser());
                kh.setSfdrjg("0");
                kh.setCreateDepartment(cght.getCreateDepartment());
                kh.setCreateOrgan(cght.getCreateOrgan());
                kh.setJs(number);
                kh.setRkjs(number);
                kh.setSbgs(cght.getSbgs());
                kh.setCggs(cght.getSbgs());
                kh.setGys(cght.getHzf());
                kh.setCgdmx(cgdmx);
                kh.setPxh(i);
                kh.setResource_serial_number_1(resource_serial_number.trim());
                kh.setCshjs(number);
                kh.setCshsl(weight);
                kh.setJhjs(number);
                kh.setJhsl(weight);
                kh.setRkdh(cght.getHtbm() + "-" + i);
                kh.setXsxt_xsdh(xsxtXsdh);
                kh.setXsxt_htbm(cght.getXsxt_htbm());
                kh.setBindNo(bindNo);
                kh.setSjly("1");
                khDao.save(kh);
                khList.add(kh);
                i++;
            }
        }

        if (cgdmxList.size() > 0) {
            //生成采购单
            Cgd cgd = new Cgd();
            cgd.setLastUpdated(new Date());
            cgd.setBz("此采购单是根据" + cght.getHtbm() + "采购合同生成!");
            cgd.setCgsj(new Date());
            cgd.setFhrq(new Date());
            cgd.setJhdhrq(new Date());
            cgd.setCreateUser(cght.getCreateUser());
            cgd.setCreateDepartment(cght.getCreateDepartment());
            cgd.setCreateOrgan(cght.getCreateOrgan());
            cgd.setCggs(cght.getSbgs());
            cgd.setCght(cght);
            cgd.setDzck(cght.getCk());
            cgd.setGys(cght.getHzf());
            cgd.setCgdh(this.bmService.getCgdbm("cgrk"));
            cgd.setCglx("cgrk");
            cgd.setZt("ysp");
            cgd.setSl(cght.getSl().toString());
            cgd.setRksj(new Date());
            cgd.setRkr(cght.getSbr());
            cgd.setSbgs(cght.getSbgs());
            cgd.setSbbm(cght.getSbbm());
            cgd.setSbr(cght.getSbr());
            cgd.setYrk(true);
            cgd.setLj(cght.getLj());
            cgd.setEndFlag(true);
            cgd.setCgdmxList(cgdmxList);
            cgd.setKhList(khList);
            cgdDao.save(cgd);
        }
    }

    /**
     * 生成销售单 A20160413zhp
     */
    private void saveXsd(Xsht xsht, Jydd jydd) {
        if (null == xsht || null == xsht.getId()) {
            throw new RuntimeException("运营系统返回，销售合同为空，逻辑错误！");
        }
        Xsd xsd = new Xsd();
        List<Xsmx> xsmxList = new ArrayList<Xsmx>();
        if (jydd.getGoodses() != null) {
            int i = 1;
            for (Goodses goodses : jydd.getGoodses()) {
                String bindNo = goodses.getResource_serial_number_1().trim(); //捆绑号
                String xsxtXsdh = goodses.getPurchase_contract_no();
                Integer number = Tools.NullToInteger(goodses.getQuantity());//件数
                Double weight = CalcUtils.round(Double.valueOf(goodses.getMeasure()), 6);//重量
                Double hsj = CalcUtils.round(Tools.NullToDouble(goodses.getPrice()), 4);//含税价
                Xsmx xsmx = new Xsmx();
                xsmx.setLastUpdated(new Date());
                xsmx.setBhsj(CalcUtils.round(hsj / 1.17, 4));
                xsmx.setHsj(hsj);
                xsmx.setSjdj(hsj);
                xsmx.setXsxt_xsdh(xsxtXsdh);
                xsmx.setXsxt_htbm(xsht.getXsxt_htbm());
                xsmx.setBindNo(bindNo);
                Sjzdz sjzdz = this.sjzdzDao.get(22L);
                xsmx.setJzfs(sjzdz);
                Gg gg = this.ggDao.findByPro(goodses.getGoods_name(), goodses.getSpec(), goodses.getMetarial());
                xsmx.setJtwz(gg);
                xsmx.setJs(number);
                xsmx.setSbsl(weight);
                xsmx.setCk_sbsl(weight);
                xsmx.setCk_js(number);
                xsmx.setCreateUser(xsht.getCreateUser());
                xsmx.setCreateDepartment(xsht.getCreateDepartment());
                xsmx.setCreateOrgan(xsht.getCreateOrgan());
                xsmx.setMxh((long) i);
                xsmxDao.save(xsmx);
                xsmxList.add(xsmx);

                i++;
            }
        }

        xsd.setLastUpdated(new Date());
        xsd.setBz("此销售单是根据" + xsht.getHtbm() + "销售合同生成!");
        Date now = new Date();
        xsd.setSxsj(now);// 开单日期，销售时间
        xsd.setFhsj(now);// 计划发货时间
        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(now);//设置当前日期
        calendar.add(Calendar.MONTH, 1);//将当前日期加一个月
        xsd.setJhsj(calendar.getTime());// 预定交货时间
        Sjzdz fyzr = sjzdzDao.get(42L);// 20160414 发运责任，目前都是自提
        xsd.setFyzr(fyzr);
        xsd.setFhfs("self");// 20160414 放货方式，默认自提
        xsd.setCreateUser(xsht.getCreateUser());
        xsd.setCreateDepartment(xsht.getCreateDepartment());
        xsd.setCreateOrgan(xsht.getCreateOrgan());
        xsd.setXsht(xsht);
        xsd.setOrderId(xsht.getOrderId());
        xsd.setThck(xsht.getCk());
        xsd.setKh(xsht.getHzf());// 客户
        xsd.setXsgs(xsht.getWlfgs());// 销售公司
        xsd.setSbgs(xsht.getSbgs());// 申报公司
        xsd.setSbgs(xsht.getSbgs());
        xsd.setCreateOrgan(xsht.getSbgs());
        xsd.setCreateDepartment(xsht.getSbgs());
        xsd.setXsdh(this.bmService.getXsdbm("htxs"));
        xsd.setXslx("htxs");// 合同销售
        xsd.setZt("ybc");// ysp
        xsd.setSl(xsht.getSl());
        xsd.setSbgs(xsht.getSbgs());
        xsd.setSbbm(xsht.getSbbm());
        xsd.setSbr(xsht.getSbr());
        xsd.setLj(xsht.getLj());
        xsd.setEndFlag("true");// true
        xsd.setXsmxList(xsmxList);
        xsdDao.save(xsd);
    }

    /**
     * 验证买家在交易系统的登陆名是否为空
     * 验证保证金是否满足校验，保证金金额>=订单总额*保证金比例
     * 验证订单是否存在
     *
     * @param khqc
     * @param ddze
     * @param order_sn
     * @param goodses
     */
    private String checkData(String khqc, Double ddze, String order_sn, List<Goodses> goodses) {
        String result = "0";
        if (StringUtils.isBlank(khqc)) {
            result = "[{\"code\" :\"1\",\"message\":\"运营系统返回，买家客户为空，order_sn:" + order_sn + "\"}]";
            return result;
        } else if (!checkGoodses(goodses)) {
            result = "[{\"code\" :\"1\",\"message\":\"运营系统返回，存在材料号为空情况，order_sn:" + order_sn + "\"}]";
            return result;
        } else {
            Qyjg qyjg = this.qyjgDao.findQyjgByQc(khqc);
            if (null == qyjg) {
                result = "[{\"code\" :\"1\",\"message\":\"运营系统返回，买家不存在：" + khqc + "\"}]";
                return result;
            }
        }
        return result;
    }

    /**
     * 判断材料号是否为空
     *
     * @param goodses
     * @return
     */
    private boolean checkGoodses(List<Goodses> goodses) {
        boolean bool = true;
        for (Goodses gds : goodses) {
            String bindNo = Tools.NullToString(gds.getResource_serial_number_1());
            if (StringUtils.isBlank(bindNo)) {
                bool = false;
                break;
            }
        }
        return bool;
    }

    /**
     * 保存销售结算信息
     *
     * @param xml
     */
    @Transactional
    public String saveXsSettleInfo(String xml) {
        List<XsSettle> list = XmlUtil.parseList(xml, XsSettle.class);
        for (XsSettle xsSettle : list) {
            xsSettle.setCreateDate(DateUtil.curDateStr14());
            this.xsSettleDao.save(xsSettle);
        }

        return "OK";
    }

    /**
     * 接收销售系统订单信息（统计挂牌量用）
     *
     * @param param
     * @return
     */
    @Transactional
    public String saveXsOrderInfo(String param) {
        List<XsOrder> list = XmlUtil.parseList(param, XsOrder.class);
        for (XsOrder xsOrder : list) {
            XsOrder inDb;
            try {
                inDb = xsOrderDao.getByOrderItemNum(xsOrder.getOrderItemNum());
            } catch (NonUniqueResultException e) {
                throw new RuntimeException("更新失败！订单号已有多条数据：" + xsOrder.getOrderItemNum());
            }
            if (inDb == null) {
                xsOrder.setCreateDate(DateUtil.curDateStr14());
                this.xsOrderDao.save(xsOrder);
            } else {
                inDb.setUpdateDate(DateUtil.curDateStr14());
                inDb.setSpec(xsOrder.getSpec());
                inDb.setOrderWt(xsOrder.getOrderWt());
                inDb.setOrderAmt(xsOrder.getOrderAmt());
                inDb.setCompanyName(xsOrder.getCompanyName());
                inDb.setFactoryName(xsOrder.getFactoryName());
                inDb.setSignDate(xsOrder.getSignDate());
                inDb.setDeliveryDate(xsOrder.getDeliveryDate());
                inDb.setProdName(xsOrder.getProdName());
                inDb.setGoodsName(xsOrder.getGoodsName());
                inDb.setShopSign(xsOrder.getShopSign());
                inDb.setSellUserName(xsOrder.getSellUserName());
                inDb.setBuyUserName(xsOrder.getBuyUserName());
                inDb.setOrderNum(xsOrder.getOrderNum());
                xsOrderDao.save(inDb);
            }
        }
        return "OK";
    }

    /**
     * 统计销售系统成交量
     *
     * @param dateStart
     * @param dateEnd
     * @return
     */
    @Transactional
    public String countSettleWt(String dateStart, String dateEnd) {
        Map<String, Object> map = this.xsSettleDao.countSettleWtByDate(dateStart, dateEnd).get(0);
        return "{\"code\" :\"0\"," + "\"message\":\"查询成功\"," +
                "\"settleWt\":\"" + Tools.NullToString(map.get("SETTLE_WT")) + "\"," +
                "\"settleAmt\":\"" + Tools.NullToString(map.get("SETTLE_AMT")) + "\"}";
    }

    /**
     * 统计销售系统挂牌量
     *
     * @param dateStart
     * @param dateEnd
     * @return
     */
    public String countOrderWt(String dateStart, String dateEnd) {
        Map<String, Object> map = this.xsOrderDao.countOrderWtByDate(dateStart, dateEnd).get(0);
        return "{\"code\" :\"0\"," + "\"message\":\"查询成功\"," + "\"orderWt\":\"" + Tools.NullToString(map.get("ORDER_WT"))
                + "\",\"orderAmt\":\"" + Tools.NullToString(map.get("ORDER_AMT")) + "\"}";
    }

    /**
     * 查询指定日期的销售系统最新订单
     */
    public String getXSOrderItems(String orderDate) {
        List<Map<String, Object>> list = xsOrderDao.getXSOrderItems(orderDate);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", "0");
        resultMap.put("message", "查询成功");
        resultMap.put("rows", list);
        Map<String, Object> map = this.xsOrderDao.countOrderWtByDate("", "").get(0);
        resultMap.put("totalOrderWt", Tools.NullToString(map.get("ORDER_WT")));
        resultMap.put("totalOrderAmt", Tools.NullToString(map.get("ORDER_AMT")));
        String today = DateUtil.curDateStr8();
        String yesterday = DateUtil.toDateStr8(DateUtil.addDays(new Date(), -1));
        map = this.xsOrderDao.countOrderWtByDate(today, "").get(0);
        resultMap.put("todayOrderWt", Tools.NullToString(map.get("ORDER_WT")));
        resultMap.put("todayOrderAmt", Tools.NullToString(map.get("ORDER_AMT")));
        map = this.xsOrderDao.countOrderWtByDate(yesterday, today).get(0);
        resultMap.put("yesterdayOrderWt", Tools.NullToString(map.get("ORDER_WT")));
        resultMap.put("yesterdayOrderAmt", Tools.NullToString(map.get("ORDER_AMT")));
        return new Gson().toJson(resultMap);
    }

    /**
     * 取消交易订单<br/>居中结算订单在交易系统取消时调用
     * <br/>处理交易订单及明细，采购合同及明细，销售合同及明细，采购单及明细、卡号，销售单及明细
     * <br/>A20160427zhp
     */
    @Transactional
    public String cancelJydd(String order_sn) throws Exception {
        Date now = new Date();
        // 交易订单
        Jydd jydd = jyddDao.checkOrderSn(order_sn);
        if (jydd != null) {
            jydd.setDeleted(1);
            jydd.setLastUpdated(now);
            jyddDao.save(jydd);
            // 交易订单明细
            String hql = " update Goodses set deleted=1,lastUpdated=? where jydd.id=?";
            Query query = jyddDao.getSession().createQuery(hql);
            query.setDate(0, now);
            query.setLong(1, jydd.getId());
            query.executeUpdate();
        }
        // 采购合同
        Cght cght = cghtDao.findUniqueByProperty("xsxt_htbm", order_sn);// 交易系统orderSn
        if (cght != null) {
            if (!"ybc".equals(cght.getZt())) {
                throw new RuntimeException("运营系统采购合同状态已变更！不允许取消！交易订单号：" + order_sn + "，采购合同号：" + cght.getHtbm());
            }
            cght.setDeleted(1);
            cght.setLastUpdated(new Date());
            cghtDao.save(cght);
            cghtDao.deleteHtmx(cght.getId());// 采购合同明细
            // 采购单
            Cgd cgd = cgdDao.findUniqueByProperty("cght.id", cght.getId());
            if (cgd != null) {
                cgd.setDeleted(1);// 采购单不校验状态
                cgd.setLastUpdated(new Date());
                cgdDao.save(cgd);
            }
            // 采购购单明细和卡号都关联了采购单和采购合同，可以跳过采购单，用采购合同id执行sql
            // 采购单明细
            String hql = "update Cgdmx set deleted=1,lastUpdated=? where cght.id=?";
            Query query = cghtDao.getSession().createQuery(hql);
            query.setDate(0, now);
            query.setLong(1, cght.getId());
            query.executeUpdate();
            // 卡号
            hql = "update Kh set deleted=1,lastUpdated=? where cght.id=?";
            query = cghtDao.getSession().createQuery(hql);
            query.setDate(0, now);
            query.setLong(1, cght.getId());
            query.executeUpdate();
        }
        // 销售合同
        Xsht xsht = xshtDao.findUniqueByProperty("xsxt_htbm", order_sn);// 交易系统orderSn
        if (xsht != null) {
            if (!"ybc".equals(xsht.getZt())) {
                throw new RuntimeException("运营系统销售合同状态已变更！不允许取消！交易订单号：" + order_sn + "，销售合同号：" + xsht.getHtbm());
            }
            xsht.setDeleted(1);
            xsht.setLastUpdated(new Date());
            xshtDao.save(xsht);
            xshtDao.deleteHtmx(xsht.getId());// 销售合同明细
            // 销售单
            Xsd xsd = xsdDao.findUniqueByProperty("xsht.id", xsht.getId());
            if (xsd != null) {
                if (!"ybc".equals(xsd.getZt())) {
                    throw new RuntimeException("运营系统销售单状态已变更！不允许取消！交易订单号：" + order_sn + "，销售单号：" + xsd.getXsdh());
                }
                xsd.setDeleted(1);
                xsd.setLastUpdated(new Date());
                xsdDao.save(xsd);
                xsdDao.deleteXsmx(xsd.getId());// 销售单明细
            }
        }
        if (jydd == null) {
            return "处理成功，没有这个订单";
        } else if (cght == null) {
            return "处理成功，没有对应的采购合同";
        } else
            return "操作成功";
    }


    /**
     * 居中结算，查询是否可以放货
     *
     * @param order_sn
     * @return
     */
    @Transactional
    public String queryContractPayment(String order_sn) {
        String result;
        // 查询交易订单
        Jydd jyddTemp = this.jyddDao.checkOrderSn(order_sn);
        // 采购合同
        Cght cght = cghtDao.findUniqueByProperty("xsxt_htbm", order_sn);
        if (null == jyddTemp || null == cght) {
            result = "{\"code\":\"1\",\"message\":\"没有查询到对应的交易订单！\"}";
        } else if (null != jyddTemp.getDingdan_type() && jyddTemp.getDingdan_type().equals("1")) {
            // 判断采购合同模式是否属于赎货
            result = "{\"code\":\"1\",\"message\":\"居中结算-》在线赎货功能，由运营通知仓储放货！\"}";
        } else {
            List<Jzjs> jzjsList = this.jzjsDao.checkHtJzjs(cght.getId());
            Double htzje = cght.getHsze();
            for (Jzjs jzjs : jzjsList) {
                Sfk sfk = this.skshDao.get(jzjs.getSk().getId());
                Double sytx = 0d;
                if (htzje <= jzjs.getYe()) {
                    if (sfk.getFkfs().getZ().equals("承兑")) {
                        // 使用贴息
                        sytx = (htzje / jzjs.getYe()) * jzjs.getTx();
                        jzjs.setTx(CalcUtils.round(sytx, 2));
                    }
                    jzjs.setYe(CalcUtils.round(jzjs.getYe() - htzje, 2));
                    htzje = 0d;
                    jzjs.setZt("1");
                    // 使用金额
                    Double syje = htzje + sytx;
                    sfk.setYe(CalcUtils.round(sfk.getYe() - syje, 2));
                    sfk.setZt("ytz");
                } else {
                    htzje -= jzjs.getYe();
                    jzjs.setYe(0d);
                    jzjs.setZt("1");
                    sfk.setYe(0d);
                    sfk.setZt("ytz");
                }
                this.skshDao.save(sfk);
                this.jzjsDao.save(jzjs);
            }

            if (htzje > 0) {
                throw new RuntimeException("货款不足不能放货！交易订单号：" + order_sn);
            } else {
                result = "{\"code\":\"0\",\"message\":\"可以放货！\"}";
            }
        }
        return result;
    }

    @Autowired
    public void setGdDao(GdDao gdDao) {
        this.gdDao = gdDao;
    }

    @Autowired
    public void setXsdDao(XsdDao xsdDao) {
        this.xsdDao = xsdDao;
    }

    @Autowired
    public void setJyddDao(JyddDao jyddDao) {
        this.jyddDao = jyddDao;
    }

    @Autowired
    public void setBmService(BmService bmService) {
        this.bmService = bmService;
    }

    @Autowired
    public void setXshtDao(XshtDao xshtDao) {
        this.xshtDao = xshtDao;
    }

    @Autowired
    public void setCghtDao(CghtDao cghtDao) {
        this.cghtDao = cghtDao;
    }

    @Autowired
    public void setGgDao(GgDao ggDao) {
        this.ggDao = ggDao;
    }

    @Autowired
    public void setSjzdzDao(SjzdzDao sjzdzDao) {
        this.sjzdzDao = sjzdzDao;
    }

    @Autowired
    public void setSjzdzService(SjzdzService sjzdzService) {
        this.sjzdzService = sjzdzService;
    }

    @Autowired
    public void setSjzdsyDao(SjzdsyDao sjzdsyDao) {
        this.sjzdsyDao = sjzdsyDao;
    }

    @Autowired
    public void setCgdmxDao(CgdmxDao cgdmxDao) {
        this.cgdmxDao = cgdmxDao;
    }

    @Autowired
    public void setKhDao(KhDao khDao) {
        this.khDao = khDao;
    }

    @Autowired
    public void setCgdDao(CgdDao cgdDao) {
        this.cgdDao = cgdDao;
    }

    @Autowired
    public void setCkDao(CkDao ckDao) {
        this.ckDao = ckDao;
    }

    @Autowired
    public void setXsSettleDao(XsSettleDao xsSettleDao) {
        this.xsSettleDao = xsSettleDao;
    }

    @Autowired
    public void setXsOrderDao(XsOrderDao xsOrderDao) {
        this.xsOrderDao = xsOrderDao;
    }

    @Autowired
    public void setQyjgDao(QyjgDao qyjgDao) {
        this.qyjgDao = qyjgDao;
    }

    @Autowired
    public void setBmDao(BmDao bmDao) {
        this.bmDao = bmDao;
    }

    @Autowired
    public void setPmDao(PmDao pmDao) {
        this.pmDao = pmDao;
    }

    @Autowired
    public void setWebserviceTransService(WebserviceTransService webserviceTransService) {
        this.webserviceTransService = webserviceTransService;
    }

    @Autowired
    public void setXsmxDao(XsmxDao xsmxDao) {
        this.xsmxDao = xsmxDao;
    }

    @Autowired
    public void setNbgsDao(NbgsDao nbgsDao) {
        this.nbgsDao = nbgsDao;
    }

    @Autowired
    public void setJzjsDao(JzjsDao jzjsDao) {
        this.jzjsDao = jzjsDao;
    }

    @Autowired
    public void setSkshDao(SkshDao skshDao) {
        this.skshDao = skshDao;
    }
}
